/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlconvert.reader;

import java.io.File;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import xmlconvert.internalStructure.Group;

/**
 *
 * @author o.rybyanskyy
 */
public class Reader {
    
    private static Logger LOG = Logger.getLogger(Reader.class);

    private Document xml;
    
    public static Reader createReader(String fileName){
          try {
		File fXmlFile = new File(fileName);
		DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
                if (LOG.isDebugEnabled()){LOG.debug("xml document read from file [" + fileName + "].");}
                return new Reader(doc);
          } catch (Exception e){
              LOG.error("Error while trying to read xml file [" + fileName + "]. " + e.getMessage());
              return null;
          }
    }
    
    private Reader(Document d){
        xml = d;
    }
    
    public static void main(String[] a){
        
        // correct path:  d:\\ash\\jprojects\\NetBeansProjects\\xmlConvert\\src\\testData\\source_sample_PS.xml
        // alternative path (another format) d:\\ash\\jprojects\\NetBeansProjects\\xmlConvert\\src\\testData\\target_sample_keypass.xml
        // another test: e:\\My Folder\\Pass_xml.xml
        
        Reader theOne = Reader.createReader("e:\\My Folder\\Pass_xml.xml");
        Group Storage = theOne.populateStorage("Storage");
    }

    private Group populateStorage(String name){
        
        Group group = Group.createGroup(name);
 
        Item [] folders = getFolders();
        
        if (folders != null){
        
        for (int i=0; i<folders.length; i++){ //iterating through folders
            
            Item [] records = getRecords(folders[i].getElement());
            if (records != null){ 
                for (int k=0; k<records.length; k++){ //iterating through records
                    
                    List<String[]> lst = getFields(records[k].getElement());
                    
                    if (lst!=null){
                        
                    } else{
                        for (int f=0; f<lst.size(); f++){ //iterating through fields
                            System.out.println("          " + lst.get(f)[0] + ": " + lst.get(f)[1] + ".");
                        }
                    }
                    
                }
            }
        }
        }
        return group;
    }

    

    public List<String[]> getFields(Element rootNode){
        FieldContainer fc = new FieldContainer();
        
        Element entries = (Element) rootNode.getElementsByTagName("items").item(0);
        NodeList itemList = entries.getElementsByTagName("item");
        if (itemList.getLength() == 0){
            return null;
        }
        
        for (int i = 0; i < itemList.getLength(); i++) {
        Element e = (Element) itemList.item(i);
        String name = e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
        String value = e.getElementsByTagName("value").item(0).getFirstChild().getNodeValue();
        fc.addField(name, value);
        }
        
        return fc.getItems();
    }
    
    
    public Item[] getFolders(){
        Item[] folders = null;
        
        NodeList nList = xml.getElementsByTagName("folder");
        if (nList.getLength() != 0){
            folders = new Item[nList.getLength()];
        } else {
            return null;
        }
        
        for (int i = 0; i < nList.getLength(); i++) {
            Element e = (Element) nList.item(i);
            String s = e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
            folders[i] = new Item(s,e);
            }
        
        return folders;
    }
    
    
    public Item[] getRecords(Element subRoot){
        Item[] records = null;
        
        Element entries = (Element) subRoot.getElementsByTagName("entries").item(0);
        NodeList entryList = entries.getElementsByTagName("entry");
        if (entryList.getLength() != 0){
            records = new Item[entryList.getLength()];
        } else {
            return null;
        }
        
        for (int i = 0; i < entryList.getLength(); i++) {
        Element e = (Element) entryList.item(i);
        String s = e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
        records[i] = new Item(s,e);
        }
        
        return records;
    }
    
    
}
